<template>
  <div class="card">
    <div class="card-body">
      <!-- 相当于对posts里面的每一个post都定义一个div -->
      <!-- 必须要用key让每一个post都是唯一的 -->
      <div v-for="post in posts.posts" :key="post.id">
        <div class="card single-post" >
          <div class="card-body">{{ post.content }}
            <button v-if="is_me" type="button" @click="delete_a_post(post.id)" class="btn btn-danger btn-sm">删除</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { computed } from 'vue';
import { useStore } from 'vuex';
import $ from 'jquery';
export default {
  name: 'UserProfilePosts',
  props: {
    posts: {
      type: Object, // 数据类型
      required: true, // 必填
    },
    user: {
      type: Object, // 数据类型
      required: true, // 必填
    },
  },
  setup(props,context){
    const store = useStore();
    const is_me= computed(() => { // 计算属性，判断是否是当前登录用户在看主页
      return store.state.user.id===parseInt(props.user.id);// userId是字符串类型，要转换成整数
    });
    const delete_a_post = (post_id) => {
      $.ajax({
        url:"https://app165.acapp.acwing.com.cn/myspace/post/",
        type:"DELETE",
        headers:{
          "Authorization": "Bearer " + store.state.user.access,
        },
        data:{
          post_id:post_id,
        },
        success(resp){
          if(resp.result=="success"){
            context.emit("delete_a_post",post_id); // 触发父组件的delete_a_post事件
          }
        }
      })
    };
    return {
      is_me,
      delete_a_post, // 删除帖子函数
    }
  }
}
</script>

<style>
.single-post {
  margin-bottom: 10px;
}
button{
  float: right;
}
</style>